# -*- coding: UTF-8 -*-

import markdown
import yaml

from jinja2 import Template
from jinja2 import Environment
from jinja2 import FileSystemLoader

import pygments_extension
jinja2_env = Environment(extensions=[pygments_extension.PygmentsExtension])
jinja2_env.filters['date_to_xmlschema'] = pygments_extension.date_to_xmlschema

class ParserFile:
    """
    Parse file by extracting its header part and content part and get variable
    found into header part. content part can be render in HTML too. 
    """
    def __init__(self, file_name):
        self.md = markdown.Markdown()
        self.file_name = file_name
        self.find_first = False
        self.find_second = False
        self.header_file = list()
        self.content_file = list()
        self._extract()

    def _extract(self):
        open_file = open(self.file_name).readlines()

        for line in open_file:
            if line.startswith('---'):
                if self.find_first == False:
                    self.find_first = True
                else:
                    self.find_second = True
            else:
                if self.find_second:
                    self.content_file.append(unicode(line, 'utf-8'))
                else:
                    self.header_file.append(unicode(line, 'utf-8'))

    def has_header(self):
        """
        Tell whether this file has header or not.
        """
        return self.find_first and self.find_second and len(self.header_file) > 0

    def has_content(self):
        """
        Tell whether this file has content or not.
        """
        return len(self.content_file) > 0

    def is_post(self):
        """
        Todo
        """
        pass

    def parse_header(self):
        """
        Convert YAML code of header part to python object.
        """
        return yaml.load(str().join(self.header_file))

    def parse_content(self):
        """
        Parse extracted content to render it as HTML.
        """
        html = jinja2_env.from_string(self.md.convert(str().join(self.content_file)))

        #TODO: Utiliser par contre jinja2_env.get_template dans le cas de fichier à récupérer.
        return html.render(test = u'Ceci est un test…')

